package org.csu.onlineedubackend.mapper;

import org.apache.ibatis.annotations.*;
import org.csu.onlineedubackend.entity.GroupAdmin;
import org.csu.onlineedubackend.entity.User;

import java.util.List;

@Mapper
public interface GroupAdminMapper {
    
    @Insert("INSERT INTO group_admins (group_id, user_id, created_at) " +
            "VALUES (#{groupId}, #{userId}, NOW()) " +
            "ON DUPLICATE KEY UPDATE created_at = NOW()")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(GroupAdmin groupAdmin);
    
    @Select("SELECT * FROM group_admins WHERE id = #{id}")
    GroupAdmin findById(Long id);
    
    @Select("SELECT * FROM group_admins WHERE group_id = #{groupId} AND user_id = #{userId}")
    GroupAdmin findByGroupAndUser(@Param("groupId") Long groupId, @Param("userId") Integer userId);
    
    @Select("SELECT * FROM group_admins WHERE group_id = #{groupId}")
    List<GroupAdmin> findByGroupId(Long groupId);
    
    @Select("SELECT * FROM group_admins WHERE user_id = #{userId}")
    List<GroupAdmin> findByUserId(Integer userId);
    
    @Delete("DELETE FROM group_admins WHERE group_id = #{groupId} AND user_id = #{userId}")
    int deleteByGroupAndUser(@Param("groupId") Long groupId, @Param("userId") Integer userId);
    
    @Select("SELECT u.* FROM users u " +
            "JOIN group_admins ga ON u.id = ga.user_id " +
            "WHERE ga.group_id = #{groupId}")
    List<User> findAdminsByGroupId(Long groupId);
    
    @Select("SELECT COUNT(*) > 0 FROM group_admins WHERE group_id = #{groupId} AND user_id = #{userId}")
    boolean isGroupAdmin(@Param("groupId") Long groupId, @Param("userId") Integer userId);

    @Select("SELECT user_id FROM group_admins WHERE group_id = #{groupId}")
    List<Integer> findAdminIdsByGroupId(Long groupId);

    @Delete("DELETE FROM group_admins WHERE group_id = #{groupId}")
    int deleteByGroupId(Long groupId);
} 